package com.leetcode.array.binarysearch.demo1;

/**
 * @Author Zan
 * @Create 2024/5/7 22:53
 * @ClassName: Test1
 * @Description : https://leetcode.cn/problems/binary-search/  二分查找
 */
public class Test1 {
    public static void main(String[] args) {

    }
}

class Solution {
    public int search(int[] nums, int target) {
        // 避免当 target 小于nums[0] nums[nums.length - 1]时多次循环运算
        // 下面这个if是提升运算速度的，因为是有序数组
        if (target < nums[0] || target > nums[nums.length - 1]) {
            return -1;
        }
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int middle = (left + right) / 2;
            if (nums[middle] > target) { // 在左边
                right = middle - 1;
            } else if (nums[middle] < target) {
                left = middle + 1;
            } else {
                return middle;
            }
        }
        return -1;
    }
}